import { EventDispatcher } from "../../base/event/EventDispatcher";
import { app } from "../../base/typings/global";


export type argType = string | boolean | number;

export class EnterOptionParser {
    protected _options:any;
    constructor(options:any){
        this._options = options;
    }

    /**
     * 是否匹配对应的来源渠道场景
     * @param scenes 
     * @returns 
     */
    isFromScene(scenes:string[]|string):boolean {
        if(typeof scenes == "string"){
            return this.channelScene == scenes;
        }
        return scenes.includes(this.channelScene);
    }

    /**
     * 来源的渠道场景
     */
    get channelScene():string {
        return this.getOption('scene') ? this.getOption('scene') + "" : "0";
    }

    /**
     * 来源的渠道
     */
    get channelSource():string {
        return this._options.query ? (this._options.query.channel || "default") : "default";
    }

    /**
     * 获取启动配置项
     * @param key 支持xx.xx递归索引，任何一级不存在返回null
     * @returns 
     */
    getOption(key:string):any {
        let keyArr:string[] = key.split(".");
        let parent = this._options;
        for (let i = 0; i < keyArr.length; i++) {
            const key = keyArr[i];
            parent = parent[key];
            if(!parent){
                return null;
            }
        }
        return parent;
    }

    getAllOption():any {
        return this._options || {};
    }
}

/**
 * 平台基类
 */
export class IPublisher extends EventDispatcher {
    static TYPE_HL:string = "HL";
    static TYPE_DEV:string = "DEV";
    static TYPE_H5:string = "H5";
    static TYPE_TT:string = "tt";
    static TYPE_233:string = "233";
    private static appId:string = "";
    private static appVersion:string = "";

    protected _type:string;
    protected _enterOptions:EnterOptionParser;
    protected _installOptions:EnterOptionParser;
    //安装来源
    private static INSTALL_SOURCE_KEY = "INSTALL_SOURCE_KEY";

    static custom(appId:string, version:string="未获取到版本号"):{new ():IPublisher} {
        IPublisher.appId = appId;
        IPublisher.appVersion = version;
        return IPublisher;
    }
    

    /**
     * 初始化平台
     * @param type 平台标视
     * @param config 平台配置 app.PublisherConfig
     * @returns 
     */
    init(type: string): IPublisher {
        this._type = this._type || type;
        app.App.onShow(this._onAppShow, this);
        return this;
    }

    protected _onAppShow(info:{query:{},scene:string|number}):void {
        this._initEnterOptions(info);
    }
    /**
     * 获取发行商名称，Develop保留位开发环境
     */
    get type(): string {
        return this._type;
    }
    /**
     * 获取发行商下的APPID
     */
    get appId(): string {
        return IPublisher.appId || window.location.pathname;
    }
    /**
     * 获取版本
     */
    get appVersion(): string {
        return IPublisher.appVersion || window.location.search;
    }

    /**
     * 平台初始化
     * @param caller 
     * @param onSuccess 
     * @param onFail 
     */
    initSDK(caller?: any, onSuccess?: Function, onFail?: Function): void {
        this._init();
        
        this._listenError();
        console.log(`[initSDK] ${this.type}`);
        onSuccess && onSuccess.apply(caller);
    }

    private _init():void {
        if(!app.storage.getGValue(IPublisher.INSTALL_SOURCE_KEY)){
            app.storage.setGValue(IPublisher.INSTALL_SOURCE_KEY, app.publisher.publisher.enterOptions.getAllOption());
        }
    }
    
    private _listenError():void {
        app.publisher.publisher.onError((...error:any[])=>{
            app.publisher.analytics.error(JSON.stringify(error));
        })
    }

    /**
     * 获取启动信息
     * @param plat 
     * @returns 
     */
    get enterOptions():EnterOptionParser {
        return this._enterOptions || this._initEnterOptions();
    }

    /**
     * 安装来源
     */
        get installOptions():EnterOptionParser {
        if(!this._installOptions) {
            this._installOptions = new EnterOptionParser(app.storage.getGValue(IPublisher.INSTALL_SOURCE_KEY, app.publisher.publisher.enterOptions.getAllOption()));
        }
        return this._installOptions;
    }

    /**
     * 获取启动参数
     * @returns 
     */
    protected _initEnterOptions(info?:any):EnterOptionParser {
        return this._enterOptions = new EnterOptionParser(info||{});
    }

    /**
     * 订阅推送
     * @param subscribeMsgIds 订阅消息模板ID列表
     * @returns 
     */
    async subscribeMessage(subscribeMsgIds:string[]):Promise<boolean> {
        return this._subscribeMessage(subscribeMsgIds);
    }

    protected async _subscribeMessage(subscribeMsgIds:string[], plat?:any):Promise<boolean> {
        return new Promise<boolean>((resolve)=>{
            if (!plat) {
                resolve(false);
                return;
            }
            if (plat.requestSubscribeMessage) {
                if(subscribeMsgIds.length == 0){
                    resolve(true);
                    return;
                }
                app.publisher.analytics.report("subscribe_show", {name:subscribeMsgIds[0]});
                plat.requestSubscribeMessage({
                    tmplIds:subscribeMsgIds,
                    success:(res:{errMsg:string, [tmplId:string]:'accept'|'reject'|'ban'|'filter'|string})=>{
                        console.log("订阅成功");
                        app.publisher.analytics.report("subscribe", {name:subscribeMsgIds[0], msg:"", code:0});
                        resolve(true);
                    },
                    fail:(error)=>{
                        console.warn(`订阅失败, msg:${error.errMsg}, code:${error.errCode}`);
                        app.publisher.analytics.report("subscribe", {name:subscribeMsgIds[0], msg:error.errMsg, code:error.errCode});
                        resolve(false);
                    }
                })
                return;
            }
            resolve(false);
        })
    }
    
    /**
     * 进入平台界面
     */
    showView(viewName:string, caller?: any, onClose?: Function): void {
        console.log(`进入${this.type}平台界面：${viewName}`);
    }

    onError(call:(...error:any[])=>void):void {

    }

    offError(call:(...error:any[])=>void):void {
        
    }
    
    /**
     * 退出
     */
    exit(): void {
        console.log(`退出平台：${this.type}`);
    }
}

    

